//
//  JPComposeController.swift
//  JPWeibo
//
//  Created by 哇咔咔 on 2016/10/1.
//  Copyright © 2016年 jp. All rights reserved.
//

import UIKit
import SVProgressHUD

let publicMargin = 8


@available(iOS 9.0, *)
class JPComposeController: UIViewController {
    
    //  MARK: -- 懒加载
    //  发送按钮
    private lazy var sendButton: UIButton = {
        let button = UIButton()
        button.addTarget(self, action: #selector(btnSendAction), for: .touchUpInside)
        button.setBackgroundImage(UIImage(named: "common_button_orange"), for: .normal)
        button.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), for: .highlighted)
        button.setBackgroundImage(UIImage(named: "common_button_white_disable"), for: .disabled)
        button.setTitle("发送", for: .normal)
        button.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        button.setTitleColor(UIColor.white, for: .normal)
        button.setTitleColor(UIColor.gray, for: .disabled)
        button.size = CGSize(width: 45, height: 35)
        
        return button
    }()
    
    //  标题
    private lazy var titleLbel: UILabel = {
        let label = UILabel(textColor: UIColor.darkGray, fontSize: 16)
        
        if let name = JPUserInfoViewModel.sharedUserInfoViewModel.userInfo?.name {
            let title = "发微博\n" + name
            
            let range = (title as NSString).range(of: name)
            
            let attributeStr: NSMutableAttributedString = NSMutableAttributedString(string: title)
            attributeStr.addAttributes([NSFontAttributeName: UIFont.systemFont(ofSize: 12), NSForegroundColorAttributeName: UIColor.brown], range: range)
            
            label.attributedText = attributeStr
        }
        
        label.numberOfLines = 0
        label.textAlignment = .center
        label.sizeToFit()
        
        return label
    }()

    //  textView
    fileprivate lazy var textView: JPComposeTextView = {
        let textView = JPComposeTextView()
        textView.font = UIFont.systemFont(ofSize: 14)
        textView.placeHolderLabel.text = "别低头,绿帽会掉~别低头,绿帽会掉~别低头,绿帽会掉~别低头,绿帽会掉~别低头,绿帽会掉~"
        textView.alwaysBounceVertical = true
        
        return textView
    }()
    //  底部工具栏
    fileprivate lazy var toolBar: JPComposeToolBar = JPComposeToolBar()
    //  图片视图
    fileprivate lazy var pictureView: JPComposePictureView = {
        let picture = JPComposePictureView()
        picture.backgroundColor = self.view.backgroundColor
        return picture
    }()
    //  表情键盘
    lazy var emotionKeyBoard: JPComposeEmotionKeyBoard = {
        let view = JPComposeEmotionKeyBoard()
        view.size = CGSize(width: self.textView.size.width, height: 216)
        return view
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
    }
    
    private func setupUI() {
        
        NotificationCenter.default.addObserver(self, selector: #selector(keyBoardFrameChanged(noti:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
        
        NotificationCenter.default.addObserver(self, selector: #selector(emotionKeyBoardDidSelected(noti:)), name: Notification.Name(DidSelectedEmotionNotification), object: nil)
        
        self.view.backgroundColor = UIColor.white
        textView.delegate = self
        
        self.navigationItem.titleView = titleLbel
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: sendButton)
        self.navigationItem.rightBarButtonItem?.isEnabled = false
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: #selector(cancelSenStatus))
        
        view.addSubview(textView)
        view.addSubview(pictureView)
        view.addSubview(toolBar)
        
        textView.snp_makeConstraints { (make) in
            make.top.equalTo(self.view)
            make.left.equalTo(self.view)
            make.right.equalTo(self.view)
            make.height.equalTo(200)
        }
        
        pictureView.snp_makeConstraints { (make) in
            make.top.equalTo(textView.snp_bottom).offset(publicMargin)
            make.left.equalTo(textView.snp_left).offset(publicMargin)
            make.right.equalTo(textView.snp_right).offset(-publicMargin)
            make.height.equalTo(pictureView.snp_width)
        }
        
        toolBar.snp_makeConstraints { (make) in
            make.bottom.equalTo(view)
            make.leading.equalTo(textView)
            make.trailing.equalTo(textView)
            make.height.equalTo(35)
        }
        
        toolBar.callBack = { [weak self] (type: JPComposeToolBarButtonType) in
            switch type {
            case .picture:
                print("图片")
                self?.didSelectedPicture()
            case .mention:
                print("@")
            case .trend:
                print("#")
            case .emoticon:
                print("表情")
                self?.didSelectedEmoji()
            case .add:
                print("加号")
            }
            
        }
        
        pictureView.lastCellCallBack = {
            self.didSelectedPicture()
        }
        
        
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    //  点击表情键盘
    @objc private func emotionKeyBoardDidSelected(noti: Notification) {
        
        guard let emotion = noti.object as? JPEmotion else {
            return
        }
        
        textView.insterEmotion(emotion: emotion)
        
    }
    
    //  取消发微博
    @objc private func cancelSenStatus() {
        textView.resignFirstResponder()
        dismiss(animated: true, completion: nil)
    }
    
    //  toolBar和键盘的联动
    @objc private func keyBoardFrameChanged(noti: NSNotification) {
        let frame = (noti.userInfo?[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
        
        let duration = (noti.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
        
        toolBar.snp_updateConstraints { (make) in
            make.bottom.equalTo(view.snp_bottom).offset(-(ScreenHeight - frame.origin.y))
        }
        
        UIView.animate(withDuration: duration) { 
            self.view.layoutIfNeeded()
        }
    }
    
    //  发送微博
    @objc private func btnSendAction() {
        let token = JPUserInfoViewModel.sharedUserInfoViewModel.accessToken!
        
        SVProgressHUD.show()
        
        let status = textView.adjustTextViewEmotionToString()
        
        if pictureView.isHidden {
            JPNetworkTool.sharedNetworkTool.update(access_token: token, status: status, callBack: { (_, error) in
                if error != nil {
                    SVProgressHUD.showInfo(withStatus: "网络请求异常")
                    return
                }
                
                self.textView.resignFirstResponder()
                self.dismiss(animated: true, completion: nil)
                SVProgressHUD.showSuccess(withStatus: "发送成功")
            })
        }else {
            JPNetworkTool.sharedNetworkTool.upload(access_token: token, status: status, image: pictureView.images.first!, callBack: { (_, error) in
                
                if error != nil  {
                    SVProgressHUD.showInfo(withStatus: "网络请求异常")
                    return
                }
                
                self.textView.resignFirstResponder()
                self.dismiss(animated: true, completion: nil)
                SVProgressHUD.showSuccess(withStatus: "发送成功")
            })
            
        }
    }
    
    
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

//  MARK: --    处理toolbar按钮点击的逻辑
@available(iOS 9.0, *)
extension JPComposeController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    
    //  处理点击emoji逻辑
    func didSelectedEmoji() {
        if textView.inputView == nil {
            textView.inputView = emotionKeyBoard
            toolBar.changedButtonIcon(isEmotion: true)
        }else {
            textView.inputView = nil
            toolBar.changedButtonIcon(isEmotion: false)
        }
        
        textView.becomeFirstResponder()
        textView.reloadInputViews()
        
    }
    
    //  处理点击图片逻辑
    func didSelectedPicture() {
        
        let imagePictureCtr = UIImagePickerController()
        //  设置代理
        imagePictureCtr.delegate = self
        
        //  是否执行传入的来源类型
        if UIImagePickerController.isSourceTypeAvailable(.camera) {
            imagePictureCtr.sourceType = .camera
        } else {
            imagePictureCtr.sourceType = .photoLibrary
        }
        
        //  判断是否支持前置设置头
        
        if UIImagePickerController.isCameraDeviceAvailable(.front) {
            //
            print("支持前置摄像头")
        }
        
        if UIImagePickerController.isCameraDeviceAvailable(.rear) {
            //
            print("支持后置摄像头")
        }
        
        //  允许编辑
        //        imagePictureCtr.allowsEditing = true
        
        self.present(imagePictureCtr, animated: true, completion: nil)
        
    }
    
    //  MARK: -- UIImagePickerControllerDelegate -> 实现代码方法后不会给我们调用dismis需要自己手动调用
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        //  取消
        picker.dismiss(animated: true, completion: nil)
    }
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        //  选中那张图片
        //UIImagePickerControllerEditedImage 获取编辑的图片
        //UIImagePickerControllerOriginalImage 获取原始图片
        
        
        let image = info["UIImagePickerControllerOriginalImage"]! as! UIImage
        //  获取压缩后的图片
        let scaleImage = image.scaleImage(scaleWidth: 200)
        //  添加压缩后的图片显示
        pictureView.addImage(image: scaleImage)
    
        picker.dismiss(animated: true, completion: nil)

    }
}

@available(iOS 9.0, *)
extension JPComposeController: UITextViewDelegate {
    func textViewDidChange(_ textView: UITextView) {
        //  判断是否有内容,然后确定是否可用
        navigationItem.rightBarButtonItem?.isEnabled = textView.hasText
    }
    
    
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        //  失去第一响应者
        self.view.endEditing(true)
    }
}
